import React from 'react';
import PropTypes from 'prop-types';

import BaseComponent from './baseComponent.js';
import { numberFromString, numberBettween } from '../../utils/func';
import minusIcon from '../../../assets/images/home/minus.png';
import plusIcon from '../../../assets/images/home/plus.png';

class NumberInput extends BaseComponent {
  constructor(props) {
    super(props);
    this.numberChanged = this.numberChanged.bind(this);
    this.checkNumber = this.checkNumber.bind(this);
    this.clickMinus = this.clickMinus.bind(this);
    this.clickPlus = this.clickPlus.bind(this);
  }

  numberChanged(e) {
    const value = e.target.value;
    console.log('value', value);
    const { onNumberChange } = this.props;
    if (value.length !== 0) {
      const number = numberFromString(value);
      // onNumberChange(numberBettween({
      //   value: number,
      //   min,
      //   max,
      // }));
      onNumberChange(number);
    } else {
      onNumberChange(0);
    }
  }

  checkNumber(e) {
    const { min, max, onNumberChange } = this.props;
    const number = numberFromString(e.target.value);
    onNumberChange(numberBettween({
      value: number,
      min,
      max,
    }));
  }

  clickMinus() {
    const { number, min, onNumberChange } = this.props;
    onNumberChange(Math.max(min, number - 100));
  }

  clickPlus() {
    const { number, max, onNumberChange } = this.props;
    onNumberChange(Math.min(max, number + 100));
  }

  render() {
    const { number } = this.props;
    return (
      <div className="number-input">
        <img src={minusIcon} className="icon" alt="" onClick={this.clickMinus} />
        <input type="tel" onChange={this.numberChanged} onBlur={this.checkNumber} value={number} />
        <img src={plusIcon} className="icon" alt="" onClick={this.clickPlus} />
      </div>
    );
  }
}

NumberInput.defaultProps = {
  number: 0,
};

NumberInput.propTypes = {
  number: PropTypes.number,
  onNumberChange: PropTypes.func.isRequired,
  max: PropTypes.number.isRequired,
  min: PropTypes.number.isRequired,
};

export default NumberInput;

